<?PHP
require_once("GameData.php");
require_once("Winners.php");

/*
Regular Expression patterns used in:

functions were created with http://www.txt2re.com
*/

class AFLGAme {
	var $HTeamName = "";
    var $HTeamRecord = "";
    var $HTeamScore = "";
    var $ATeamName = "";
    var $ATeamRecord = "";
    var $ATeamScore = "";
	var $TimeRemaining = "";
	
	function AFLGAme() {
	}
}

/* Scrapes the ESPN Wireless site. */
class ESPNScraper {

    /*  The html is read into here, and is consumed as we go.  */
    var $htmlString = "";
    var $sportsml = "";
    var $rssString = "";
    var $CurrWeek = "";
    var $tempDay = "";
    var $League = "";
	var $Season = "";
    
	/****************************************************************************************/
    function ESPNScraper() {
		$this->League = "NFL";	//Use NFL by default
    }
    
    /****************************************************************************************/
    function SetCurrWeek($newWeek)
    {
		$this->CurrWeek = $newWeek;
    }
	/****************************************************************************************/
    function SetSeasonYear($newYear)
    {
		$this->Season = $newYear;
    }
    /****************************************************************************************/
    function SetLeague($newLeague)
    {
		$this->League = $newLeague;
    }
    /****************************************************************************************/
    
    /*   Add the header to the xml.   */
    function addHeader()
    {
        $this->sportsml .= "<?xml version='1.0'?>\n<?xml-stylesheet type=\"text/xsl\" href=\"http://football.joshhughes.com/css/sportsml2html.xsl\"?>\n";
        //$this->sportsml .= "<!DOCTYPE sports-content SYSTEM \"e:/src/xmlsports/sportsml/1.0/dtd/sportsml-core.dtd\">";//todo www url?
        //$this->sportsml .= "\n";
        $this->sportsml .= "<sports-content>\n";
        $this->sportsml .= "<sports-metadata doc-id=\"".$this->getDocId()."\" date-time=\"".$this->getCurrentDateTimeStamp()."\" sports-title=\"".$this->Season." ".$this->League." Week ".$this->CurrWeek." Games\" publisher=\"".$this->getPublisherName()."\" language=\"en-US\"/>\n\n";
        
        $this->rssString .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\">\n";
        $this->rssString .= "<channel>
			  <title>Recent ".$this->League." Scores</title>
			  <link>http://football.joshhughes.com/".$this->League."/rss</link>
			  <description>Recent ".$this->League." Scores</description>
			  <language>en-us</language>
			  <pubDate>".$this->getCurrentDateTimeStamp()."</pubDate>		
			  <lastBuildDate>".$this->getCurrentDateTimeStamp()."</lastBuildDate>
			  <generator>Custom Script From JoshHughes.com</generator>";
		   
    }//end addHeader()    
    
	/****************************************************************************************/
    /*   Add the footer to the xml.   */
    function addFooter()
    {
        $this->sportsml .= "</sports-content>\n";
        $this->rssString .= "</channel></rss>";
    }//end addFooter()
    
	/****************************************************************************************/	
    /*   "Date-timestamp for the document, normalized to ISO 8601: YYYYMMDDTHHMMSS+HHMM (preferred)
     * YYYYMMDDTHHMMSSZ (alternative). Use YYYYMMDD000000+HHMM when no time is available"   */
    function getCurrentDateTimeStamp()
    {
		$formattedDate = date('Ymd;');
		$formattedTime = date('his');
        return $formattedDate."T".$formattedTime;
    }
	/****************************************************************************************/
    /*   "The often-unique ID of the document, tracked by publishers."   */
    function getDocId()
    {
        return date('U');
    }
    
	/****************************************************************************************/  
	/*   Add an event to the markup.   */
    function addEvent($data)
    {
		//add new SportsML event
        $this->sportsml .= "<sports-event>\n";
        $this->sportsml .= "<event-metadata event-status=\"";
        //add new RSS item
        $this->rssString .= "<item>";
        $myRSSTitle = $this->computeTeamKey($data->visitingTeam)." ".$data->visitingTeamScore." ".$this->computeTeamKey($data->homeTeam)." ".$data->homeTeamScore;
        $this->rssString .= "<title><![CDATA[$myRSSTitle]]></title>";
        $this->rssString .= "<description><![CDATA[<p>$myRSSTitle</p>]]></description>";
        
        
        if ($data->STATUS == "STATUS_UPCOMING")
        {
            $this->sportsml .= "pre-event\" start-date-time=\"".$data->startDate;
        }
        else if ($data->STATUS == "STATUS_IN_PROGRESS")
        {
            $this->sportsml .= "mid-event\" time-left=\"".$data->timeLeft." ".$data->period;
			/* Only in the 1st quarter, check to see if picks were emailed for the games starting when this one did. */
			//if ($data->period == "1st")
				checkPickEmailer($this->computeTeamKey($data->homeTeam),$this->computeTeamKey($data->visitingTeam), $this->League);
				
        }
        else if ($data->STATUS == "STATUS_FINAL")
        {
            $this->sportsml .= "post-event";
			//SetWinner in League Schedule Table of Database
			setGameWinner($this->computeTeamKey($data->homeTeam), $data->homeTeamScore, $this->computeTeamKey($data->visitingTeam), $data->visitingTeamScore, $this->CurrWeek, $this->League);
        }
        else
        {
            echo "unknown event-status code: ".$data->STATUS;
        }
        
        //todo event-state-attributes-american-football
        $this->sportsml .= "\" />\n";

        //VISTOR TEAM
        $this->sportsml .= "<team>\n";
        $this->sportsml .= "<team-metadata alignment=\"away\" team-key=\"".$this->computeTeamKey($data->visitingTeam)."\" >";
        $this->sportsml .= "<name first=\"".$data->visitingTeam."\" />";
        $this->sportsml .= "</team-metadata>\n";
        if ($data->STATUS != "STATUS_UPCOMING")
        {
            $this->sportsml .= "<team-stats score=\"".$data->visitingTeamScore."\" ";
            if ($data->STATUS == "STATUS_FINAL")
            {
                $this->sportsml .= "event-outcome=\"".$this->decideWinLoss($data->visitingTeamScore, $data->homeTeamScore)."\" ";
            }
            $this->sportsml .= "/>\n";
        }
        $this->sportsml .= "</team>\n";

        //HOME TEAM
        $this->sportsml .= "<team>\n";
        $this->sportsml .= "<team-metadata alignment=\"home\" team-key=\"".$this->computeTeamKey($data->homeTeam)."\" >";
        $this->sportsml .= "<name first=\"".$data->homeTeam."\" />";
        $this->sportsml .= "</team-metadata>\n";
        if ($data->STATUS != "STATUS_UPCOMING")
        {
            $this->sportsml .= "<team-stats score=\"".$data->homeTeamScore."\" ";
            if ($data->STATUS == "STATUS_FINAL")
            {
                $this->sportsml .= "event-outcome=\"".$this->decideWinLoss($data->homeTeamScore, $data->visitingTeamScore)."\" ";
            }
            $this->sportsml .= "/>\n";
        }
        $this->sportsml .= "</team>\n";

		//close SportsML Event
        $this->sportsml .= "</sports-event>\n\n";
        //Close RSS item
        $this->rssString .= "<link>http://football.joshhughes.com/</link>";
		$this->rssString .= "<pubDate>".date('D, j M Y H:i:s O')."</pubDate>";
        $this->rssString .= "</item>";
        
    }
	/****************************************************************************************/
    /*   Basic 3-letter team-key computation. Tested with NFL.
     *
     * passing "Minnesota" returns "MIN"
     * passing "New Orleans" returns "NO"
     * passing "NY Jets" returns "NYJ" (special cases for NY teams)
     *
     * @param fullname full team city name   */
    function computeTeamKey($fullname)
    {
        $space = strpos(trim($fullname), " ");
        if ($space)
        {
            if (strtoupper(substr($fullname, 0, 2)) == "NY")		//"NY" + first letter of the 2nd word
            {                
                return strtoupper("NY".substr($fullname,3, 1));
            }
			else if (strtoupper(substr($fullname, 0, 2)) == "ST")
			{
				return "STL";
			}
            else		//first letter of each word
            {
                return strtoupper(substr($fullname, 0, 1).substr($fullname, $space+1, 1));
            }
        }
        else	//first 3 letters
        {
			//Special Case in AFL where two teams have same first 3 letters
			if (($fullname == "Columbus") || ($fullname == "Colorado"))
				return strtoupper(substr($fullname, 0, 4));	//first 4 letters
			else	
				return strtoupper(substr($fullname, 0, 3));	//first 3 letters
        }
    }
	/****************************************************************************************/
    function decideWinLoss($mine, $yours)
    {
        if ($mine > $yours) {
            return "win";
        } else if ($yours > $mine) {
            return "loss";
        } else {
            return "tie";
        }
    }
	/****************************************************************************************/
    function retrieveData()
    {
		switch ($this->League) {
		case "NFL"://National Football League
			{
			if ($this->CurrWeek <= 17)
				$url = "http://mobileapp.espn.go.com/nfl/mp/html/scoreboard?year=".$this->Season."&season=2&week=".$this->CurrWeek."&dvc=1";
			else
				$url = "http://mobileapp.espn.go.com/nfl/mp/html/scoreboard?year=".$this->Season."&season=3&week=".($this->CurrWeek - 17)."&dvc=1";
			}
			break;
		case "NCAA"://College Football top 25
			$url = "http://mobileapp.espn.go.com/ncf/mp/html/scoreboard?year=".$this->Season."&season=3&week=1&dvc=1";
			break;
		case "AFL"://Arena Football League
			{
			$url = "http://sports.espn.go.com/extra/afl/scoreboard?year=".$this->Season."&week=".$this->CurrWeek."&season=2";
			}
			break;
		}
		echo "URL = $url<br/>";
        //MLB
        #$url = "http://proxy.espn.go.com/mlb/wireless/html/scoreboard?dvc=1";
        //NBA
        #$url = "http://proxy.espn.go.com/nba/wireless/html/scoreboard?dvc=1";
        //NHL
        #$url = "http://proxy.espn.go.com/nhl/wireless/html/scoreboard?dvc=1";
        //College Basketball Top 25
        #$url = "http://proxy.espn.go.com/ncb/wireless/html/scoreboard?dvc=1";
        if (!($fp = fopen($url, "r")))
        {
			echo "could not open XML input";
			exit;
		}
		
		while ($data = fread($fp, 4096))
		{
			$this->htmlString .= $data;
		}
    }
    
	/****************************************************************************************/
    function scrape()
    {
		//$this->CurrWeek = $newWeek;
		
        $this->retrieveData();
        
        $this->addHeader();

        $this->addScores();

        $this->addFooter();
        
        return $this->sportsml;
    }//end scrape()
    
	/****************************************************************************************/
    function addScores()
    {
		switch ($this->League)
		{
		case "NFL"://National Football League
			$this->NFLchunkIntoDaysOfScores();
			break;
		case "AFL"://Arena Football League
			$this->AFLchunkIntoDaysOfScores();
			break;
		}
    }//end addScores() 
	
	/****************************************************************************************/
    function getPublisherName()
    {
        return "ESPN";
    }
	################################  LEAGUE-SPECIFIC FUNCTIONS  ################################
    ##### National Football League - NFL #####
		/****************************************************************************************/
		function NFLchunkIntoDaysOfScores()
		{   
			$pattern='()((?:SUNDAY|MONDAY|TUESDAY|WEDNESDAY|THURSDAY|FRIDAY|SATURDAY))(\\s+)((?:JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER))(\\s+)([-+]?\\d+)(<\\/b>)';
			preg_match_all("/".$pattern."/is", $this->htmlString,$tempArray, PREG_SET_ORDER);
			if ($matches = preg_split("/".$pattern."/is", $this->htmlString,-1,PREG_SPLIT_OFFSET_CAPTURE))
			{	
				for ($i = 1; $i < sizeof($matches); $i++)
				{
					$this->tempDay = $tempArray[$i-1][0];	//Save Date of Game For Later
					$this->processOneNFLDayOfScores($matches[$i][0]);
				}
			}
			else
			{
				echo "Nothing Found";
			}
		}//end NFLchunkIntoDaysOfScores()
		
		/****************************************************************************************/
		function processOneNFLDayOfScores($chunk)
		{
			//echo "chunk = $chunk";
			$pattern = '<font size=[-+]?\\d+>(.*?)<\\/font><br>(.*?)<br>';	# Tag 4
			if ($c = preg_match_all("/".$pattern."/is", $chunk, $matches2, PREG_SET_ORDER))
			{
				foreach ($matches2 as $val)
					$this->processOneNFLGame(strip_tags($val[1]), strip_tags($val[2]));
			}//end IF
			else
			{
				echo "no scores found for this day, ".$chunk;
			}//end ELSE
		}//end processOneNFLDayOfScores
		
		/****************************************************************************************/
		function processOneNFLGame($field1, $field2)
		{
		   // echo "found <b>".trim($field1)."</b>, ".trim($field2)."<br/>";
			
			$data = new GameData();
			
			//Process field1
			if ((trim($field1) == "Final") || (trim($field1) == "Final / OT") || (trim($field1) == "Final-OT") || (trim($field1) == "End Overtime"))	//if game is Final or F-OT (overtime)
			{
				$data->STATUS = "STATUS_FINAL";
			}
			else if (strpos($field1, " ET")) //if ET (Eastern Time) is found in string, the game hasn't started.
			{
				$data->STATUS = "STATUS_UPCOMING";
				$pieces = explode(" ", strip_tags($this->tempDay));
				$data->startDate = ucfirst(strtolower(substr($pieces[0], 0, 3))).". ".ucfirst(strtolower(substr($pieces[1], 0, 3))).". ".$pieces[2]." - ".$field1;
				$data->startDate = str_replace(" ET", "", $data->startDate);
			}
			else
			{
				$data->STATUS = "STATUS_IN_PROGRESS";
				if (trim($field1) == "Halftime")
				{
					$data->timeLeft = "";
					$data->period = "H";
				}
				else
				{
					$data->timeLeft = substr($field1, 0, strpos($field1, " "));
					$data->period = substr($field1, strpos($field1, " ")+1+0);
				}
			}
			
			//Process field2
			if ($data->STATUS == "STATUS_UPCOMING")
			{
				$data->visitingTeam = trim(substr($field2, 0, strpos($field2, " at ")));
				$data->homeTeam = trim(substr($field2, (strpos($field2, " at ")+4)));
			}
			else
			{
				//(Wildcard team name)(any integer)(Wildcard team name)(any integer)
				$pattern = '(.*?)([-+]?\\d+)(.*?)([-+]?\\d+)';
				if ($c = preg_match_all("/".$pattern."/is", $field2, $matches3, PREG_SET_ORDER))
				{
					foreach ($matches3 as $val)
					{
						$data->visitingTeam = trim($val[1]);
						$data->visitingTeamScore = trim($val[2]);
						$data->homeTeam = trim($val[3]);
						$data->homeTeamScore = trim($val[4]);
					}
				}//end IF
				else
				{
					echo "no scores found for this game, ".$field2;
				}//end ELSE
			}
	
			$this->addEvent($data);			
			
		}//end processOneNFLGame
    
	##### Arena Football League - AFL #####
		/****************************************************************************************/
		function AFLchunkIntoDaysOfScores()
		{   
			echo "In AFLchunkIntoDaysOfScores()..............<br/>";
			#$pattern='()((?:SUNDAY|MONDAY|TUESDAY|WEDNESDAY|THURSDAY|FRIDAY|SATURDAY))(\\s+)((?:JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER))(\\s+)([-+]?\\d+)(<\\/b>)';
			$pattern='(.)(\\s+)((?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|Tues|Thur|Thurs|Sun|Mon|Tue|Wed|Thu|Fri|Sat|Today))(.)(\\s+)((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t|ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?))(\\s+)([-+]?\\d+)(.)(\\s+)((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])(\\s+)(.)';
			preg_match_all("/".$pattern."/is", $this->htmlString,$tempArray, PREG_SET_ORDER);
			if ($matches = preg_split("/".$pattern."/is", $this->htmlString,-1,PREG_SPLIT_OFFSET_CAPTURE))
			{	
				for ($i = 1; $i < sizeof($matches); $i++)
				{
					$this->tempDay = substr($tempArray[$i-1][0], 2,-1);	//Save Date of Game For Later
					$this->processOneAFLDayOfScores($matches[$i][0]);
				}
			}
			else
			{
				$pattern='(-)(\\s+)(Today)(\')(s)( )(Games)(-)';
				preg_match_all("/".$pattern."/is", $this->htmlString,$tempArray, PREG_SET_ORDER);
				if ($matches = preg_split("/".$pattern."/is", $this->htmlString,-1,PREG_SPLIT_OFFSET_CAPTURE))
				{
					for ($i = 1; $i < sizeof($matches); $i++)
					{
						$this->tempDay = date("l, F j, Y");	//Save Date of Game For Later	(Example: Friday, March 21, 2008)
						$this->processOneAFLDayOfScores($matches[$i][0]);
					}
				}
				else
				{
					echo "Nothing Found";
				}
			}
		}//end AFLchunkIntoDaysOfScores()
		
		/****************************************************************************************/
		function processOneAFLDayOfScores($chunk)
		{
			echo "&nbsp; &nbsp; &nbsp; In processOneAFLDayOfScores(chunk)..............<br/>";
			//echo "chunk = $chunk";
			//Create an Array to hold Game information
			$TodaysGames = array();
			
			###  Get Team Names & Records  ###
			$pattern = '(<div class="teams">)(<table>)(<tr>)(<[^>]+>)(.*?)(<\\/td>)(<\\/tr>)(<tr>)(<td class="teamLine">)(<[^>]+>)(.*?)(<\\/a>)(<[^>]+>)(\\s+)(.*?)(<\\/span>)(<\\/td>)(<\\/tr>)(<tr>)(<td class="teamLine">)(<[^>]+>)(.*?)(<\\/a>)(<[^>]+>)(\\s+)(.*?)(<\\/span>)(<\\/td>)(<\\/tr>)(<\\/table>)(<\\/div>)';
			$GNum = 0;	//GameNum
			
			if ($c = preg_match_all("/".$pattern."/is", $chunk, $matches2, PREG_SET_ORDER))
			{
				foreach ($matches2 as $val)
				{
					$TodaysGames[$GNum] =& new AFLGame();
					$TodaysGames[$GNum]->TimeRemaining = strip_tags($val[5]);
					$TodaysGames[$GNum]->ATeamName = strip_tags($val[11]);
					$TodaysGames[$GNum]->ATeamRecord = strip_tags($val[15]);
					$TodaysGames[$GNum]->HTeamName = strip_tags($val[22]);
					$TodaysGames[$GNum]->HTeamRecord = strip_tags($val[26]);
					$GNum++;
				}
			}//end IF
			else
			{
				echo "no teams found for this day, ".$chunk."<br/>";
			}//end ELSE
			
			###  Get SCores  ###
			$pattern = '(<)(td)(\\s+)(class)(=)("tScoreLine")(\\s+)(id)(=)(".*?")(>)([-+]?\\d+)(<\\/td>).*?';
			$pattern .= '(<)(td)(\\s+)(class)(=)("tScoreLine")(\\s+)(id)(=)(".*?")(>)([-+]?\\d+)(<\\/td>)';
			$GNum = 0;	//GameNum
			
			if ($c = preg_match_all("/".$pattern."/is", $chunk, $matches2, PREG_SET_ORDER))
			{
				foreach ($matches2 as $val)
				{
					$TodaysGames[$GNum]->ATeamScore = strip_tags($val[12]);
					$TodaysGames[$GNum]->HTeamScore = strip_tags($val[25]);
					$GNum++;
				}
			}//end IF
			else
			{
				echo "no scores found for this day, ".$chunk."<br/>";
			}//end ELSE
			
			//Send each Game to be Processed
			foreach ($TodaysGames as $Game)
			{
				//echo $Game->ATeamName." (".$Game->ATeamRecord.") [".$Game->ATeamScore."] at ".$Game->HTeamName." (".$Game->HTeamRecord.") [".$Game->HTeamScore."]<br/>";
				$this->processOneAFLGame($Game->TimeRemaining, $Game->ATeamName,$Game->ATeamScore,$Game->HTeamName,$Game->HTeamScore);
			}
			
		}//end processOneAFLDayOfScores
		
		/****************************************************************************************/
		function processOneAFLGame($TimeRemain, $ATeam, $AScore, $HTeam, $HScore)
		{
			$data = new GameData();
			echo "In processOneAFLGame($TimeRemain, $ATeam, $AScore, $HTeam, $HScore)<br/>";
			//Process TimeRemain
			if ((trim($TimeRemain) == "Final") || (trim($TimeRemain) == "Final / OT") || (trim($TimeRemain) == "Final - OT") || (trim($TimeRemain) == "End Overtime"))	//if game is Final or F-OT (overtime)
			{
				$data->STATUS = "STATUS_FINAL";
				echo "...Game over...<br/>";
			}
			else if (strpos($TimeRemain, " ET")) //if ET (Eastern Time) is found in string, the game hasn't started.
			{
				$data->STATUS = "STATUS_UPCOMING";
				$pieces = explode(" ", strip_tags($this->tempDay));
				$data->startDate = ucfirst(strtolower(substr($pieces[0], 0, 3))).". ".ucfirst(strtolower(substr($pieces[1], 0, 3))).". ".substr($pieces[2], 0, -1)." - ".$TimeRemain;
				$data->startDate = str_replace(" ET", "", $data->startDate);
			}
			else
			{
				$data->STATUS = "STATUS_IN_PROGRESS";
				if (trim($TimeRemain) == "Halftime")
				{
					$data->timeLeft = "";
					$data->period = "H";
				}
				else
				{
					$data->timeLeft = substr($TimeRemain, 0, strpos($TimeRemain, " "));
					$data->period = substr($TimeRemain, strpos($TimeRemain, " ")+1+0);
				}
			}
			
			$data->visitingTeam = $ATeam;
			$data->visitingTeamScore = $AScore;
			$data->homeTeam = $HTeam;
			$data->homeTeamScore = $HScore;
			
			$this->addEvent($data);			
			
		}//end processOneAFLGame
	
}
?>
